var fs = require("fs");
var path = require('path');
var chalk = require('chalk');
var inquirer = require('inquirer');
var needle = require('needle');
// 压缩
var adm_zip = require('adm-zip');

const pluginName = 'ShopPlugin';

class ShopPlugin {

    constructor({auto = false}) {
        this.auto = auto;
    }

    apply(compiler) {
        //编译完成支持执行之后
        compiler.hooks.done.tapAsync(
            pluginName,
            (stats, callback) => {
                var shopConfigDev = require('../shopConfig-dev.js');
                fs.readdir(shopConfigDev.zipDir, (err, files) => {
                    console.log(chalk.green(`执行--->${pluginName}`));
                    // 测试商城
                    this.sendShop(shopConfigDev, files);
                })
                callback();
            }
        );
    }

    sendShop(config, files) {
        console.log(chalk.yellow(`----------读取配置文件:`));
        console.log(config);
        console.log('自动：', this.auto);
        if (this.auto) {
            this.zipFile(config, files);
        } else {
            // 询问一下
            inquirer.prompt([{
                name: 'conform',
                message: `是否要上传到商城？`,
                type: 'list',
                default: 0,
                choices: [{
                    name: '是',
                    value: 1
                }, {
                    name: '否',
                    value: 0
                }]
            }]).then((answers) => {
                if (answers.conform) {
                    this.zipFile(config, files);
                }
            })
        }
    }

    zipFile(config, files) {
        console.log("压缩文件——--")
        var count = 0;
        if (!fs.existsSync(config.outPutDir)) {
            fs.mkdirSync(config.outPutDir);
        }
        let overZipDic = config.zipDir;
        // 如果有parentDir ，则对dist进行挪动
        if (config.parentDir) {
            // 先对dist下文件进行移动
            let allDic = `${config.parentDir}/${config.zipDir}`;
            if (!fs.existsSync(allDic)) {
                fs.mkdirSync(allDic);
            }
            files.forEach((name) => {
                fs.renameSync(`${config.zipDir}/${name}`, `${allDic}/${name}`);
            })
        }

        var run = () => {
            if (count < config.sendGoods.length) {
                var good = config.sendGoods[count];
                if(good.skip){
                    count++;
                    run();
                    return;
                }
                var zip = new adm_zip();
                zip.addLocalFolder(overZipDic);

                var WZipUrl = `${config.outPutDir}/${good.name}.zip`;
                zip.writeZip(WZipUrl, () => {
                    count++;
                    run();
                });
            } else {
                this.sendHttp(config, files);
            }
        }
        run();
    }

    sendHttp(config, files) {
        console.log("发送商城——--")
        // 检查需要发送的文件
        var zipFiles = fs.readdirSync(config.outPutDir).filter((item)=>item.indexOf('.zip')>0);
        let zipFilesCheckStr = zipFiles.join(',');
        var overSendGoods =config.sendGoods.filter((good)=> zipFilesCheckStr.indexOf(`${good.name}.zip`)>=0  && !good.skip);
        console.log(overSendGoods.map((good)=>good.name));

        var count = 0;
        var run = () => {
            if (count < overSendGoods.length) {
                var good = overSendGoods[count];
                var buffer = fs.readFileSync(`${config.outPutDir}/${good.name}.zip`);
                // 发送http上传zip文件
                var httpZipData = {
                    foo: 'bar',
                    file: {
                        buffer: buffer,
                        filename: `${good.name}.zip`,
                        content_type: 'application/octet-stream'
                    },
                    goods_id: good.goods_id,
                    user_name: config.username,
                    password: config.pwd
                };
                needle
                    .post(config.upUrl, httpZipData, {multipart: true}, function (err, resp, body) {
                        // needle will read the file and include it in the form-data as binary
                        if (!err && body.result == '1') {
                            console.log(body);
                            console.log(chalk.green(`----->【${good.name}】上传成功！`));
                            count++;
                            run()
                        } else {
                            console.log(body);
                            console.log(chalk.red(`----->【${good.name}】上传失败！`));
                        }
                    })
            }
        }


        run();
    }
}

module.exports = ShopPlugin;